﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Logging;
using Microsoft.Practices.Unity;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Net;
using Interfaces;
using Utility;

namespace Services
{
    [DataContract]
    [KnownType(typeof(ChartResult))]
    public class ChartResults : INotifyPropertyChanged, IChartResults
    {
        [DataMember] public ObservableCollection<IChartResult> Values { get { return _values; } set { _values = value; NotifyPropertyChanged("Values"); } }
        [DataMember] public IChartResult Sum { get { return _sum; } set { _sum = value; NotifyPropertyChanged("Sum"); } }
        [DataMember] public DateTime Start { get { return _start; } set { _start = value; NotifyPropertyChanged("Start"); } }
        [DataMember] public string Exchange { get { return _exchange; } set { _exchange = value; NotifyPropertyChanged("Exchange"); } }
        [DataMember] public int MarketOpenMinute { get { return _marketOpenMinute; } set { _marketOpenMinute = value; NotifyPropertyChanged("MarketOpenMinute"); } }
        [DataMember] public int Interval { get { return _interval; } set { _interval = value; NotifyPropertyChanged("Interval"); } }

        public event PropertyChangedEventHandler PropertyChanged;

        private IChartResult _sum;
        private ObservableCollection<IChartResult> _values;
        //private readonly ILoggerFacade _logger;
        private readonly IUnityContainer _container;
        private int _marketOpenMinute, _interval;
        private DateTime _start;
        private string _exchange;
        private const string _address = "http://www.google.com/finance/getprices?i=[period]&p=[days]d&f=d,o,h,l,c,v&df=cpct&q=[ticker]";
        private readonly WebClient _webClient;

        public ChartResults(IUnityContainer container) 
        {
            _container = container;
            //_logger = logger;
            _webClient = new WebClient();
        }

        public void Get(string ticker, string period, string days)
        {
            try
            {
                var res = Parse.ToJaggedArray(_webClient.DownloadString(_address.Replace("[ticker]", ticker).Replace("[period]", period).Replace("[days]", days)));

                Exchange = Parse.Split(res[0][0], '%')[1];
                MarketOpenMinute = int.Parse(Parse.Split(res[1][0], '=')[1]);
                Start = DateTime.FromOADate(int.Parse(res[7][0].TrimStart('a')) / 86400 + 25569 + (5.5 / 24)).AddMinutes(MarketOpenMinute);
                Interval = int.Parse(Parse.Split(res[3][0], '=')[1]);

                Values = new ObservableCollection<IChartResult>(); 
                Sum = (IChartResult)_container.Resolve(typeof(IChartResult));

                for (var row = 7; row < res.Count() - 1; row++)
                {
                    var result = (IChartResult)_container.Resolve(typeof(IChartResult)); 
                    result.Update(Start, MarketOpenMinute, Interval, res[row], res[row][0].StartsWith("a"), _sum);
                    Values.Add(result);
                }
            }
            catch (Exception e)
            {
                //_logger.Log(e.Message, Category.Exception, Priority.High);
            }
        }

        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}
